package com.zsh.wanandroid.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.zsh.wanandroid.utils.LogUtils;
import com.zsh.wanandroid.utils.UIUtils;

/**
 * @author zsh
 * @date 2020/3/18.
 * 功能：
 */

public abstract class BasePagerFragment extends Fragment {

    public boolean mIsPrepare = false;//视图还没准备好
    public boolean mIsVisible = false;//不可见
    public boolean mIsFirstLoad = true;//第一次加载

    public View rootView;
    public int currentPage;//当前页
    public int pageCount;//总页数
    public int cid;
    public String type;

    public boolean isDownRefresh = false;

    protected LoadService mBaseLoadService;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = UIUtils.getView(onCreateFragmentView());
            mBaseLoadService = LoadSir.getDefault().register(rootView, new com.kingja.loadsir.callback.Callback.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    onNetReload(v);
                }
            });
        }
        return mBaseLoadService.getLoadLayout();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mIsPrepare = true;
        initView(view);
        lazyLoad();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //isVisibleToUser这个boolean值表示:该Fragment的UI 用户是否可见
        if (isVisibleToUser) {
            mIsVisible = true;
            lazyLoad();
        } else {
            mIsVisible = false;
        }
    }

    protected abstract int onCreateFragmentView();

    protected abstract void initView(View view);

    protected abstract void loadNet();

    protected abstract void onNetReload(View v);

    private void lazyLoad() {
        //这里进行三个条件的判断，如果有一个不满足，都将不进行加载
        if (!mIsPrepare || !mIsVisible || !mIsFirstLoad) {
            return;
        }
        LogUtils.i("fragment网络加载");
        loadNet();
        //数据加载完毕,恢复标记,防止重复加载
        mIsFirstLoad = false;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mIsFirstLoad = true;
        mIsPrepare = false;
        mIsVisible = false;
        if (rootView != null) {
            //((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }

}
